<?php
session_start();
require_once( 'configs/config.php' );
require_once( 'lib/db.php' );
require_once( 'lib/functions.php' );
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();

if( !isset( $_GET[ 'id' ] ) && !isset( $_SESSION[ 'UID' ] ) )
{
	header( 'Location: login.php' );
}

if( isset( $_GET[ 'id' ] ) )
{
	$smarty->assign('logged_in', 'true');
	$id = $_GET[ 'id' ];
}

if( !isset( $_GET[ 'id' ] ) && isset( $_SESSION[ 'UID' ] ) )
{
	$id = $_SESSION[ 'UID' ];
	$smarty->assign('logged_in', 'true');
	$smarty->assign('self', 'true');
}

if( (isset( $_SESSION[ 'UID' ] ) && $_GET[ 'id' ] == $_SESSION[ 'UID' ] ) || $_SESSION[ 'Level' ] == $config[ 'Admin' ] )
{
	$smarty->assign('logged_in', 'true');
	$smarty->assign('admin', 'true');
	$smarty->assign('self', 'true');
}

$smarty->assign('id', $id);

$customer = $db->get_row( 'SELECT CONCAT( u.FirstName, \' \', u.LastName ) as Name, g.Name as GroupName, u.Gender, u.PhoneNumber, u.Email, u.AIM, u.YIM, u.MSN, u.Address, u.Photograph FROM users u, usergroups g WHERE u.GroupUID = g.GroupUID AND u.UserUID = ' . $id );

foreach($customer as $key => $value)
{
  $smarty->assign(strtolower($key), $value);
}

$allPayments = $db->get_results( 'SELECT DATE_FORMAT( p.Date, \'%M %e, %Y\' )as Date, ABS( p.Amount )as Amount, SIGN( p.Amount ) as Sign, p.Reason FROM payments p WHERE UserUID = ' . $id . ' ORDER BY p.Date ASC' );
//$db->debug();

for($i = 0; $i < count($allPayments); $i++)
{
  $payments[$i]['date'] = $allPayments[$i]->Date;
  $payments[$i]['sign'] = $allPayments[$i]->Sign >= 0 ? 'positive' : 'negative';
  $payments[$i]['amount'] = $allPayments[$i]->Amount;
  $payments[$i]['reason'] = $allPayments[$i]->Reason;
}

$balance = $db->get_row( 'SELECT ABS( SUM( p.Amount ) ) as Amount, SIGN( SUM( p.Amount ) ) as Sign FROM payments p WHERE UserUID = ' . $id);
$balanceSign = $balance->Sign >= 0 ? 'positive' : 'negative';
$balance = $balance->Amount;


$smarty->assign('title', 'Your Account');
$smarty->assign('payments', $payments);
$smarty->assign('balance', $balance);
$smarty->assign('balanceSign', $balanceSign);
$smarty->display('account.tpl');
?>
